package com.qqt.csr.order.service.statemachine.action.impl;

import com.google.common.collect.Lists;
import com.qqt.csr.message.event.intrasite.IntraSiteMessageEventPublisher;
import com.qqt.csr.message.event.intrasite.workorder.WorkOrderEventSource;
import com.qqt.csr.order.entity.WorkOrder;
import com.qqt.csr.order.enums.WorkOrderEventEnum;
import com.qqt.csr.order.enums.WorkOrderStatusEnum;
import com.qqt.csr.order.enums.WorkOrderTemplateType;
import com.qqt.csr.order.service.event.DynamicEvent;
import com.qqt.csr.order.service.event.DynamicEventListener;
import com.qqt.csr.order.service.event.DynamicEventSource;
import com.qqt.csr.order.service.statemachine.action.IActionPostProcessor;
import com.qqt.csr.order.service.statemachine.context.WorkOrderContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author
 */
@Slf4j
@Component
public class CreatedWorkOrderProcessor extends AbstractWorkOrderProcessor implements IActionPostProcessor {
    @Autowired
    private IntraSiteMessageEventPublisher messageEventPublisher;
    @Autowired
    private DynamicEventListener dynamicEventListener;

    @Override
    public boolean matches(WorkOrderEventEnum event) {
        return WorkOrderEventEnum.CREATED.equals(event) || WorkOrderEventEnum.CREATED_ALLOCATED.equals(event);
    }

    @Override
    public void postProcess(WorkOrderStatusEnum from, WorkOrderStatusEnum to, WorkOrderEventEnum event, WorkOrderContext context) {
        WorkOrder order = context.getToOrder();
        if (order.isNeedSysNotify() && order.isAllocated() && !order.getDesigneeId().equals(order.getCreatorId())) {
            // 直接分配了处理人，并且非自己，需要发送系统通知
            WorkOrderEventSource workOrderEventSource = new WorkOrderEventSource()
                    .setWorkOrderId(order.getId())
                    .setWorkOrderName(order.getTitle())
                    .setEventType(WorkOrderTemplateType.SET_UP_PROCESSOR)
                    .setParams(new String[]{context.getOperatorName()})
                    .setLinkUrl(StringUtils.EMPTY)
                    .setExt("{\"permission\":\""+ORDER_PROCESSOR_PERM+"\"}")
                    .setRecipientIds(Lists.newArrayList(order.getDesigneeId()));
            messageEventPublisher.publishEvent(workOrderEventSource);
        }

        recordDynamic(context, event);
    }

    /**
     * 记录动态
     *
     * @param context
     */
    private void recordDynamic(WorkOrderContext context, WorkOrderEventEnum event) {
        DynamicEventSource eventSource = new DynamicEventSource()
                .setEvent(event)
                .setOrderId(context.getToOrder().getId())
                .setProcessor(context.getOperatorName());
        dynamicEventListener.onApplicationEvent(new DynamicEvent(eventSource));
    }

}
